package com.xc.xcmanage.web.filter;

import com.xc.xcmanage.domain.dto.LoginUser;
import com.xc.xcmanage.utils.JwtUtil;
import com.xc.xcmanage.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)) {
            //请求没有携带token就放行
            filterChain.doFilter(request, response);
            return;
        }
        // 有token才解析
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            throw new RuntimeException("token非法");
        }

        // 获取 userId
        String userId = claims.getSubject();
        // 去redis中获取用户信息
        LoginUser loginUser = (LoginUser)redisCache.getCacheObject("login:" + userId);

        // loginUser为空 说明 未登录
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        // 如果存在，则把用户信息 存到 SecurityContextHolder 对象中
        // 补充权限信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
